package com.richfit.barcodesystem_cczt.activitis.adapters;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.richfit.barcodesystem_cczt.activitis.model.users.UserInfo;
import com.richfit.barcodesystem_cczt.databinding.ItemModuleBinding;
import com.richfit.barcodesystem_cczt.utils.CommonUtils;

import java.util.List;

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
    private Context context;
    private List<UserInfo.MenusBean> list;

    /**
     * 利用接口 -> 给RecyclerView设置点击事件
     */
    private ItemClickListener mItemClickListener;

    public MainAdapter(Context context, List<UserInfo.MenusBean> list) {
        this.context = context;
        this.list = list;
    }

    public void setOnItemClickListener(ItemClickListener itemClickListener) {
        this.mItemClickListener = itemClickListener;

    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        ItemModuleBinding binding = ItemModuleBinding.inflate(LayoutInflater.from(this.context));
        return new ViewHolder(binding.getRoot());
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        ItemModuleBinding binding = ItemModuleBinding.bind(holder.itemView);
        binding.modularItemName.setText(list.get(position).getName());
        binding.modularItemIcon.setBackgroundResource(CommonUtils.createModuleIcon(list.get(position).getPath()));
        // 点击事件一般都写在绑定数据这里，当然写到上边的创建布局时候也是可以的
        if (mItemClickListener != null) {
            holder.itemView.setOnClickListener(v -> {
                // 这里利用回调来给RecyclerView设置点击事件
                mItemClickListener.onItemClick(position, list.get(position));
            });
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public interface ItemClickListener {
        void onItemClick(int position, UserInfo.MenusBean menusBean);
    }

    /**
     * ViewHolder类将子项布局中所有控件绑定为一个对象，该对象包含子项布局的所有控件
     */
    static class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View itemView) {
            super(itemView);
        }
    }

}
